package com.zh.web;

import com.zh.web.vo.ResponseVO;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * @author ふわふわ
 * @version 1.0
 * @description: 文件上传
 * @date 2021/5/12 15:02
 */
@CrossOrigin
@RestController
public class UploadController {
    @PostMapping(value = "/uploading")
    public ResponseVO uploadFile(@RequestParam("filename") MultipartFile file) {

        if (file.isEmpty()) {
            return new ResponseVO<>(null,"上传文件为空",4000);
        }
        // 获取文件全名a.py
        String fileName = file.getOriginalFilename();
        // 文件上传路径
        //TODO
//        String templatePath = "F:/文档/毕业论文/code/cbp/src/main/resources/static/img/";
        String templatePath = "F:/文档/毕业论文/code/cbp/src/main/webapp/static/work/Tomcat/localhost/ROOT/";
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //获取文件名
        String prefixName = fileName.substring(0, fileName.lastIndexOf("."));
        // 解决中文问题,liunx 下中文路径,图片显示问题
        //fileName = UUID.randomUUID() + suffixName;
        File dest0 = new File(templatePath);
        File dest = new File(templatePath + fileName);
//        File dest = new File(dest0, prefixName + File.separator + fileName);
        //文件上传-覆盖
        try {
            // 检测是否存在目录
//            if (!dest0.getParentFile().exists()) {
//                dest0.getParentFile().mkdirs();
//            }
            //检测文件是否存在
//            if (dest.exists()) {
//                return new ResponseVO<>(null,"该图片已存在",4000);
//            }
            file.transferTo(dest);
            return new ResponseVO<>(null,"上传文件成功",2000);
        } catch (Exception e) {
            return new ResponseVO<>(null,"上传文件失败",4000);
        }

    }
}
